//
//  HGPreview.m
//  HGMM
//
//  Created by @HUI on 15/9/21.
//  Copyright (c) 2015年 cc. All rights reserved.
//

#import "HGPreview.h"
#import "UIView+ViewController.h"
//#import "HGRequestUtil.h"
#import "MBProgressHUD+NJ.h"
#import <AFNetworking/AFNetworking.h>
#import "LinkServers.h"


#define yozo_download_server            @"https://fir.im/YDYDcs"


@interface HGPreview ()


@end

@implementation HGPreview

-(void)show:(CDVInvokedUrlCommand *)command{
   // self.command = command;
    if (command.arguments.count !=2 || [command.arguments[0]intValue] < 1 || [command.arguments[0]intValue]>6) {
      CDVPluginResult  *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    
    BOOL isExist = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"yozooffice://"]];
    
    
    //如果不存在,跳转下载页面
    if (!isExist) {

        UIAlertController *actionVC = [UIAlertController alertControllerWithTitle:nil message:@"请下载移动阅读" preferredStyle:(UIAlertControllerStyleAlert)];

        [actionVC addAction:[UIAlertAction actionWithTitle:@"前往下载" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {

            NSURL *downloadUrl = [NSURL URLWithString:yozo_download_server];

            [[UIApplication sharedApplication] openURL:downloadUrl];

        }]];

        [actionVC addAction:[UIAlertAction actionWithTitle:@"稍后下载" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        }]];


        [self.webView.viewContoller presentViewController:actionVC animated:YES completion:^{

           CDVPluginResult  *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"下载永中阅读"];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

        }];


        return;
    }
    else
    {
        NSInteger type = [command.arguments[0] integerValue];
        if (type != 2) {
            
            UIAlertController *aler = [UIAlertController alertControllerWithTitle:@"提示" message:@"无法打开该格式文档" preferredStyle:(UIAlertControllerStyleAlert)];
            
            [aler addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                
            }]];
            
            [self.webView.viewContoller presentViewController:aler animated:YES completion:^{
                
                CDVPluginResult  *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"不支持的打开格式"];
                [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                
            }];
            
            return;
            
        }
        
        NSDictionary *dicx =  (NSDictionary *)command.arguments[1];
        NSString *serverx = [dicx objectForKey:@"server"];
        NSString *dicUrl = [dicx objectForKey:@"url"];
        NSString *dicId = [dicUrl stringByDeletingLastPathComponent];
        NSString *docName = [dicUrl lastPathComponent];
        NSString *dicType = @"";
        
        [self openFile:serverx docName:docName docId:dicId dicType:dicType command:command];
        
        }

}


-(void)openFile:(NSString *)server
        docName:(NSString *)docName
          docId:(NSString *)docId
        dicType:(NSString *)dicType
        command:(CDVInvokedUrlCommand *)command

{
    
   // HGRequestUtil *req = [HGRequestUtil sharedInstance];
    
    [MBProgressHUD showMessage:@"正在打开" toView:self.webView];
    
    [self downLoadfile:server docId:docId docName:docName SuccessBlock:^(BOOL isSuccess, NSString *docPath, NSError *error) {
    
        [MBProgressHUD hideHUDForView:self.webView animated:YES];
        
        if(isSuccess){
            
            NSString * filepath= docPath;
            NSString * fileName= [docName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSData  * fileData = [NSData dataWithContentsOfFile:filepath];
            UIPasteboard * paste=[UIPasteboard generalPasteboard];
            [paste setData:fileData forPasteboardType:fileName];
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"yozooffice://file%@",[fileName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]]];
            if (@available(iOS 10.0, *)) {
                    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                } else {
                    // Fallback on earlier versions
                    [[UIApplication sharedApplication] openURL:url];
                }
            
            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"文件打开"];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            
        }
        else
        {
            //[MBProgressHUD showSuccess:@"文件打开失败" toView:self.webView];
            [MBProgressHUD showError:@"文件打开失败" toView:self.webView];
            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"文件打开"];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            
        }

    }];
    
}

- (void)downLoadfile:(NSString *)server
               docId:(NSString *)docId docName:(NSString *)docName
        SuccessBlock: (void(^)(BOOL isSuccess,NSString *docPath,NSError *error)) successBlock{
    
    //判断是否文件存在了
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *dataFilePath = [docsdir stringByAppendingPathComponent:HGPreviewFilePath];
    NSString *_path = [NSString stringWithFormat:@"%@/%@",dataFilePath,docName];
    
    
    BOOL ishave = [fileManager fileExistsAtPath:_path];
    
    if(ishave){
        
        successBlock(YES,_path,nil);
        
        return;
        
    }

   
    NSString *host = [LinkServers shareInstance].linkhost;
     NSString *allUrl = [NSString stringWithFormat:@"http://%@:8181/HGMIDE/hgmeam?http.protocol.content-charset=UTF-8",host];
    
    NSString *url = docName;
    if(docId.length > 0)
    {
        url = [NSString stringWithFormat:@"%@/%@",docId,docName];
    }
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *downloadManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
   // NSString *requestURLString = [NSString stringWithFormat:@"%@%@",host,url];
    
    downloadManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:allUrl parameters:nil error:nil];
    [request setValue:url forHTTPHeaderField:@"hgmeam_header_url"];
    [request setValue:server forHTTPHeaderField:@"hgmeam_header_server"];

    NSURLSessionDownloadTask *downloadTask = [downloadManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        
        
        BOOL isDir = NO;
        BOOL existed = [fileManager fileExistsAtPath:dataFilePath isDirectory:&isDir];
        
        if (!(isDir && existed)) {
            [fileManager createDirectoryAtPath:dataFilePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:nil error:nil];
        NSString *pathx = [NSString stringWithFormat:@"%@/%@",HGPreviewFilePath,docName];
        
        return [documentsDirectoryURL URLByAppendingPathComponent:pathx];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        if (!error) {
            
            successBlock(YES,_path,nil);
        }else{
            successBlock(NO,nil,error);
        }
    }];
    
    [downloadTask resume];
}


@end
